/**
 * @description user store
 * @author LI
 * @date 2020-11-17 16:35
 */

import { ActionTree, Commit, GetterTree, MutationTree } from 'vuex'
import { createVNode } from 'vue'
import { LoginData } from '@/api/sys/model/userModel'
import { getAccountInfo, login, logout } from '@/api/sys/user'
import { cookies } from '@/utils/cookies'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import routers from '@/router'

export interface user {
  id: number
  loginEmail: string
  nickName: string
  photoUrl: string
}

export interface getter {
  getToken: (state?: userState) => string
  getUserInfo: (state?: userState) => user
}

export interface userState {
  token: string
  userInfo: user
}

export interface userStateInterface {
  token: string
  userInfo: user
  getters: getter
}

const state: userState = {
  token: '',
  userInfo: {} as user
}

const getters: GetterTree<userState, any> = {
  getToken(state: userState) {
    return state.token
  },
  getUserInfo(state: userState) {
    return state.userInfo
  }
}

const mutations: MutationTree<userState> = {
  SET_TOKEN: (state: userState, token: string) => {
    state.token = token
  },
  // 用户信息
  setUserInfo: (state: userState, userInfo: any) => {
    state.userInfo = userInfo
  }
}

const actions: ActionTree<any, any> = {
  async login({ commit }: { commit: Commit }, userInfo: LoginData) {
    try {
      const userData = await login(userInfo)
      if (userData.success) {
        commit('SET_TOKEN', userData.rows.token)
        cookies.set('token', userData.rows.token)
        message.success('登录成功')
      }
      return userData
    } catch (e) {
      console.log(e)
    }
  },

  // 获取用户信息
  async getAccountInfo({ commit }: { commit: Commit }) {
    try {
      const userData = await getAccountInfo()
      commit('setUserInfo', userData)
    } catch (e) {
      console.log(e)
    }
  },

  // 退出登录
  logout({ commit }: { commit: Commit }) {
    Modal.confirm({
      title: '您确定要退出登录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      okText: '确定',
      cancelText: '取消',
      onOk() {
        cookies.remove('token')
        commit('SET_TOKEN', '')
        routers.push('login')
        location.reload()
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
